<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-download"
      @click="dialogVisible = true"
    >
      成员活跃、贡献统计CSV
    </el-button>
    <el-dialog
      title="导出成员活跃、贡献统计CSV"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
      destroy-on-close
      @open="daterange = baseDaterange"
    >
      <div>
        <span class="title info-deep" style="line-height: 2rem;">关联的空间</span>
        <p>
          <el-tag type="warning" size="mini">{{ curGroup.space.title }}</el-tag>
        </p>
        <span class="title info-deep" style="line-height: 2rem;">选择时间段</span>
        <div>
          <el-date-picker
            v-model="daterange"
            type="daterange"
            unlink-panels
            align="center"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
          <p class="info">从开始日期的00:00:00到截止日期的23:59:59。<br>当统计今天的数据时，每隔2小时可重新获取</p>
        </div>
        <span class="title info-deep" style="line-height: 2rem;">评分情况</span>
        <div>
          <el-checkbox v-model="isScore">获取评分</el-checkbox>
          <div v-if="isScore" class="flex content-center">
            <div class="p-x-10">
              <div>
                创建资源
                <el-input size="mini" type="number" v-model="score.docs" style="width: 3rem;" />
                分
              </div>
              <div>
                评论回复
                <el-input size="mini" type="number" v-model="score.comments" style="width: 3rem;" />
                分
              </div>
              <div style="margin-top: 4px">
                第一名满分
                <el-input size="mini" type="number" v-model="score.full" style="width: 4rem;" />
                分
              </div>
            </div>
            <div class="p-x-10">
              <div>
                提出问题
                <el-input size="mini" type="number" v-model="score.issues" style="width: 3rem;" />
                分
              </div>
              <div>
                点赞操作
                <el-input size="mini" type="number" v-model="score.like" style="width: 3rem;" />
                分
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="m-t-16 flex content-space-between">
        <el-button type="primary" @click="getCSV" :loading="loading">下载CSV</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import FileSaver from 'file-saver';
import { formatMembersCSV } from '@/views/groups/format';
import { options1 } from '@/views/groups/show/activities/date_time_picker_options';
import SelectRelatedSpace from '@/views/groups/components/select-related-space';

const Json2csvParser = require('json2csv').Parser;

export default {
  name: 'CSV', // 获取群组成员的活跃度CSV
  components: { SelectRelatedSpace },
  props: {
    baseDaterange: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      pickerOptions: options1,
      daterange: this.baseDaterange,
      selectedSpace: {},
      isScore: false,
      score: {
        docs: 5,
        issues: 3,
        comments: 3,
        like: 1,
        full: 100,
      },
      loading: false,
    };
  },
  computed: {
    ...mapState({ curGroup: 'currentGroup' }),
    rangeStart() { return new Date(this.daterange[0]).getTime(); },
    rangeEnd() { return new Date(this.daterange[1]).getTime(); },
    // 获取CSV所需参数
    initGetParams() {
      return {
        groupId: this.$route.params.groupId,
        // spaceId: this.selectedSpace.id,
        start_at: this.rangeStart,
        end_at: this.rangeEnd,
      };
    },
  },
  methods: {
    // 获取CSV
    getCSV() {
      this.loading = true;
      this.$api.groupMembers.getCSV(this.initGetParams)
        .then((res) => {
          if (res.data.map(info => info.wait).includes(true)) setTimeout(this.getCSV, 2000);
          else {
            this.handleRes(res);
            this.loading = false;
          }
        })
        .catch(() => { this.loading = false; });
    },
    // 处理返回的信息
    handleRes(res) {
      const score = this.isScore ? this.score : undefined;
      const members = formatMembersCSV(res.data, score, this.rangeStart, this.rangeEnd);
      const parser = new Json2csvParser();
      const csvData = parser.parse(members);
      const blob = new Blob([`\uFEFF${csvData}`], { type: 'text/plain;charset=utf-8;' });
      const timeTag = this.rangeStart ? `${this.getTime(this.rangeStart)}-${this.getTime(this.rangeEnd)}` : '';
      const groupName = this.$store.state.currentGroup.title;
      const fileName = `群组【${groupName}】的成员活跃统计表 ${timeTag}.csv`;
      FileSaver.saveAs(blob, fileName);
    },
    // 获取时间
    getTime(time) {
      const thatDay = new Date(time);
      const year = thatDay.getFullYear(thatDay);
      const month = thatDay.getMonth(thatDay) + 1; // 因为是从0开始的
      const date = thatDay.getDate(thatDay); // 每个月的第几天

      return `${year}/${this.addZero(month)}/${this.addZero(date)}`;
    },
    // 处理0
    addZero(num) { return num < 10 ? `0${num}` : num; },
  },
};
</script>

<style></style>
